package com.zensun.framework.web.service;

import cn.hutool.core.util.ObjectUtil;
import com.zensun.common.constant.UserConstants;
import com.zensun.common.exception.CustomException;
import com.zensun.system.domain.SysUser;
import com.zensun.system.domain.model.LoginUser;
import com.zensun.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author gmk
 */
@Service("userDetailsByTelephoneServiceImpl")
@Slf4j
public class UserDetailsByTelephoneServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByTelePhone(phone);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", phone);
            throw new CustomException("登录手机号：" + phone + " 不存在");
        } else if (UserConstants.EXCEPTION.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", phone);
            throw new CustomException("对不起，您的手机号：" + phone + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
